// core/sdk-core.js
import { jsBridgeFactory } from '../adapter/jsbridge-factory';
import configManager from '../config/config-manager';
import { AuthManager } from '../auth/auth-manager';
import { UIManager } from '../ui/ui-manager';
import { Config } from '../utils/config';
import { MapAdapter } from '../adapter/MapAdapter';
class WebAppSDK {
  constructor(options = {}) {
    this.options = options;
    this.jsBridge = null;
    this.config = null;
    this.auth = null;
    this.ui = null;
    this.map = null;

    // this.init()
  }

  async init() {
    // 初始化配置
    const res = await configManager.init(this.options.appId);
    this.config = JSON.parse(res.data);
    console.log(
      '🚀 ~ sdk-core.js:20 ~ WebAppSDK ~ init ~  this.config:',
      this.config
    );
    this.config=new Config(this.config);
    // 初始化JSBridge
    this.jsBridge = jsBridgeFactory.getCurrentAdapter();
    console.log(
      '🚀 ~ sdk-core.js:26 ~ WebAppSDK ~ init ~ this.jsBridge:',
      this.jsBridge
    );

    // 初始化各模块
    await this.initModules();
  }

  async initModules() {
    // const configs = new Config(this.config);
    const configs =this.config
    // 认证模块
    this.auth = new AuthManager(this.jsBridge, configs);

    // UI适配模块
    console.log(
      '🚀 ~ sdk-core.js:20 ~ WebAppSDK ~ init ~  this.config:',
      this.config
    );

    console.log(
      '🚀 ~ sdk-core.js:38 ~ WebAppSDK ~ initModules ~ configs:',
      configs
    );
    this.ui = new UIManager(configs);
    this.map = new MapAdapter(configs);
console.log("模块初始化完成");
    

    // 其他业务模块...
  }

  // 统一API调用方法
  async call(method, params = {}) {
    try {
      console.log('f方法', method);

      // 前置拦截器
      // await this.beforeCall(method, params)
      console.log('aa,this.jsBridge', this.jsBridge);

      // 执行调用
      const result = await this.jsBridge.invoke(method, params);

      // 后置拦截器
      // await this.afterCall(method, params, result)

      return result;
    } catch (error) {
      // this.handleError(method, error)
      // throw error
    }
  }
  fetchData(axiosInstance, method, url, data = null, params = null) {
    this.jsBridge.fetchData(axiosInstance, method, url, data, params);
  }
  // 注册事件监听
  on(event, callback) {
    this.jsBridge.on(event, callback);
  }

  static async create(options) {
    const sdk = new WebAppSDK(options);
    await sdk.init();
    return sdk;
  }
}

// Vue插件安装
// WebAppSDK.install = function(Vue, options) {
//   const sdk = new WebAppSDK(options)

//   Vue.prototype.$sdk = sdk
//   Vue.mixin({
//     beforeCreate() {
//       this.$sdk = sdk
//     }
//   })
// }

export default WebAppSDK;
